package controllersx;

import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import lombok.SneakyThrows;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;
import java.util.UUID;

/**
 * @Author wuchao66
 * @Date 2022/7/7 10:20
 * @Version 1.0
 */
@WebServlet(name = "ServletPay",urlPatterns = "/ServletPay")
public class ServletPay extends HttpServlet {
    final String APP_ID = "2021000118671403";
    final String APP_PRIVATE_KEY = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQCfAxt4KVmD10KiwHZf0Z4WuGfX6sJT7lOhJFN2Cpc8Bs520vzVV9PTNVdfJu443OXEYw2ah9QYZuD9GKkoi4fmCpMM98/p4EtKH1Q8j9n8hwX5C3rbM3ajol6Q7jHBP9ocTbThh5qjT+RJPI0mrR9L1Zg28zfNWfd2Lb4Vjd2OttHpffEfI4TpbDGJQfeBRvZKeGvYzilghZOOCkXGWLNQ5DmWtZm1LJmZeN9LOOTXHK0bDn0MmLUKiszZiv6oJkOwOc7BhcP1q6f+9kCj8Kcvym9jIp9cDtdHFXGeDZk2GK4CuwpIEm3w3Veegf5g7YVc1OI1Y2Wnmbg9UHlblT4jAgMBAAECggEBAJQtwRto7RH/NwmTcLw6CqgBkEOVcSHlpek0gNIvbF9zuFLiqtnkznCz9IenL7etojAwXizzBqL2vBMfOAOggzPMBty+0fGQIpkgOM92/hxldxttpz895gD2/kjwr0z2w7o8b6L7Sw+FE6dr1d2E1vVERmRuokGq5QAsAEb1vNGP9CTixdpQ9n1qD3hZvz2zDHfNDTcwJz3ZKGOfBeNmo7CTfxVowM+q/PqfXha9iyUmIlaZ9KkLUnuQuYVOYKQIYMzer0sBZh3W8dTu8zp4dsZAA465VOQ5zYXvGXwrcyd41L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Gbg/RipKIuH5gqTDPfP6eBLSh9UPI/Z/IcF+Qt62zN2o6JekO4xwT/aHE204Yeao0/kSTyNJq0fS9WYNvM3zVn3di2+FY3djrbR6X3xHyOE6WwxiUH3gUb2Snhr2M4pYIWTjgpFxlizUOQ5lrWZtSyZmXjfSzjk1xytGw59DJi1CorM2Yr+qCZDsDnOwYXD9aun/vZAo/CnL8pvYyKfXA7XRxVxng2ZNhiuArsKSBJt8N1XnoH+YO2FXNTiNWNlp5m4PVB5W5U+IwIDAQAB";
    //这是沙箱接口路径,正式路径为https://openapi.alipay.com/gateway.do
    final String GATEWAY_URL ="https://openapi.alipaydev.com/gateway.do";
    final String FORMAT = "JSON";
    //签名方式
    final String SIGN_TYPE = "RSA2";
    //支付宝异步通知路径,付款完毕后会异步调用本项目的方法,必须为公网地址
    //private final String NOTIFY_URL = "http://公网地址/notifyUrl";
    final String NOTIFY_URL = "http://localhost:8080/t163jspall_war_exploded/ServletPay";//可以忽略
    //支付宝同步通知路径,也就是当付款完毕后跳转本项目的页面,可以不是公网地址
    //private final String RETURN_URL = "http://公网地址/returnUrl";
    final String RETURN_URL = "http://localhost:8080/t163jspall_war_exploded/ServletReturn";

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//乱码问题
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        //out对象
        PrintWriter out = response.getWriter();//文件流
        //刷新缓存区 关闭
        out.flush();
        out.close();
    }
    @SneakyThrows
    protected void doGet(HttpServletRequest request1, HttpServletResponse response1) throws ServletException, IOException {
        //乱码问题
        response1.setCharacterEncoding("utf-8");
        response1.setContentType("text/html;charset=utf-8");
        //out对象
        PrintWriter out = response1.getWriter();//文件流
       Random r=new Random();
      // request1.getParameter("name")
        //实例化客户端,填入所需参数
        AlipayClient alipayClient = new DefaultAlipayClient(GATEWAY_URL, APP_ID, APP_PRIVATE_KEY, FORMAT, CHARSET, ALIPAY_PUBLIC_KEY, SIGN_TYPE);
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        //在公共参数中设置回跳和通知地址
        request.setReturnUrl(RETURN_URL);
        request.setNotifyUrl(NOTIFY_URL);
        //UUID.randomUUID()
        //商户订单号，商户网站订单系统中唯一订单号，必填
        //生成随机Id  ---商品编号  付款金融  商品名称
        //雪花算法--订单编号---幂等性
        String out_trade_no = UUID.randomUUID().toString()+System.currentTimeMillis()+"";
               // new Random().nextInt(20000000)+1434+"";
        //付款金额，必填
        String total_amount =Integer.toString(r.nextInt(99999)+10000);
        //订单名称，必填
        String subject ="t163不要学习打酱油，被学校抓到拍照";
        //商品描述，可空
        String body = "还在睡觉，今天下午都不听课，我告诉你，学校说了，越是这种时候，越要上正课";
        request.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String form = "";
        try {
            form = alipayClient.pageExecute(request).getBody(); // 调用SDK生成表单
        } catch (Exception e) {
            e.printStackTrace();
        }
        response1.setContentType("text/html;charset=" + CHARSET);
        response1.getWriter().write(form);// 直接将完整的表单html输出到页面
        response1.getWriter().flush();
        response1.getWriter().close();

        out.flush();
        out.close();

    }

}
